<?php

namespace app\index\controller;

use think\Config;
use think\Controller;

class Article extends Base
{
    public function upload_api()
    {

        header('Content-Type: application/json');
//        $result = [];


        if (request()->file('image')) {
            # code...


            // 获取表单上传文件 例如上传了001.jpg
            $file = request()->file('image');


            // 移动到框架应用根目录/public/uploads/ 目录下
             $info = $file->move(ROOT_PATH . 'public' . DS . 'static/uploads');


            if ($info) {

//                Config::set('default_return_type', 'json');

//                $result['code'] = 200;
//                $result['msg'] = '上传成功 !' . $info->getSaveName();
//                $result['filename'] = $info->getFilename();


                $result = $info->getFilename();

            } else {
                // 上传失败获取错误信息
                $result['code'] = 400;
                $result['msg'] = '上传失败 !' . $file->getError();


            }
        } else {
            // 上传失败获取错误信息
            $result['code'] = 410;
            $result['msg'] = '没有选择文件';
        }

        $result =trim($result);

        // 返回上传结果
        return  str_replace("\xEF\xBB\xBF", '', $result); // 移除BOM;
     }
    public function open_answer()
    {
        $id = input('artid');
        //var_dump($id);exit();
        //$id= 52;
        $loginmember = input('loginmember');
        $serialnumber = input('serialnumber');

        if ($loginmember) {
            $data['member'] = input('loginmember');
            $data['nickname'] = input('serialnumber');

            $validate = \think\Loader::validate('openanswer');
            if ($validate->check($data)) {
                // return $this->success('登记成功！开始答题','article/index' );
                //var_dump("ok");
                //exit();

                // 获取调查的指定的条件，从limit库里，根据题目的id号
                $article_limit = \think\Db::name('article_limit')
                    ->where('articleid', $id)
                    ->find();

                // var_dump($article_limit);
                //echo $article_limit['type'];
                // exit();
                // 如果类型不大于0继续验证，否则终止验证

                // 从会员表里获取用户的ID 和 类型,根据用户的 姓名和学号
                $member = \think\Db::name('member')
                    ->where('serialnumber', $serialnumber)
                    ->where('name', $loginmember)
                    ->find();
                // var_dump($serialnumber);
                // var_dump($loginmember);
                // var_dump($member);exit();


                if ($article_limit['type'] > 0) {
                    # code...

                    //var_dump($member);
                    echo $member['type'];


                    // 对比是否在允许的类型里面 如果不是输出错误返回提示
                    if ($article_limit['type'] != $member['type']) {
                        # code...
                        return $this->error('你的类型不正确');
                    }
                }
                $memberid = $member['id'];
                session('memberid', "$memberid");
                session('loginmember', "$loginmember");
                session('serialnumber', "$serialnumber");

                // var_dump(session('memberid'));exit();
                return $this->redirect('article/index', ['artid' => $id]);
            } else {
                return $this->error($validate->getError());
            }
        } elseif (input('reset')) {
            # code...
            session('loginmember', "");
            session('serialnumber', null);
            session('loginmember', null);
            session('memberid', null);

            //return $this->error('');
            //return $this->success('','article/index', ['artid' => 53]);
            return $this->redirect('article/index', ['artid' => $id]);
        } else {
            return $this->error('请输入姓名');
        }
    }

    public function index()
    {
        $id = input('artid');

        $article_contens = \think\Db::name('article_contens')
            ->where('cate', $id)
            ->order('id')
            ->where('title', 'neq', ' ')
            ->select();


        //var_dump(count($article_contens));
        //exit();

        if (request()->isPost()) {
            $arts['open'] = "";
            //var_dump(input('post.'));
            $i = 1;
            $data = [];
            while ($i <= count($article_contens)) {
                # 统一获取的值


                // 单选时处理，如果多选进入else
                if (input('var' . $i) == 'radio') {
                    # code...
                    //var_dump(" i am raido");
                    $radiovalue = input('answer' . $i);
                    //$data['answer'.$radiovalue] = $radiovalue;
                    //var_dump('answer'.$radiovalue);exit;
                    // var_dump(session('memberid'));exit();
                    $data = [
                        'answer' . input('answer' . $i) => 1,
                        'cate' => $id,
                        'name' => session('loginmember') . time(),
                        'member' => session('loginmember'),
                        'memberid' => session('memberid'),
                        'answerid' => input('answerid' . $i),
                        'serialnumber' => session('serialnumber'),
                        'time' => time(),
                    ];


                    // 使用switch语句
                    switch (input('answer' . $i)) {
                        case "1":
                            // 如果$day等于"Monday"，执行这里的代码
                            $data['correct'] = "A";
                            break;
                        case "2":
                            // 如果$day等于"Tuesday"，执行这里的代码
                            $data['correct'] = "B";
                            break;
                        case "3":
                            // 如果$day等于"Wednesday"，执行这里的代码
                            $data['correct'] = "C";
                            break;

                        case "4":
                            // 如果$day等于"Wednesday"，执行这里的代码
                            $data['correct'] = "D";
                            break;

                        case "5":
                            // 如果$day等于"Wednesday"，执行这里的代码
                            $data['correct'] = "E";
                            break;

                        case "6":
                            // 如果$day等于"Wednesday"，执行这里的代码
                            $data['correct'] = "F";
                            break;

                        default:
                            // 如果$day的值不匹配任何case，执行这里的代码
                            break;
                    }


                    $db = '';
                    if ($radiovalue) {

                        // 查询出该试卷对应题目的得分，如果正确，获得得分
                        $data['score'] = \think\Db::name('article_contens')
                            ->where('cate', $id)
                            ->where('correct', $data['correct'])
                            ->where('id', input('answerid' . $i))
                            ->value('score')?:0;

                        $db = \think\Db::name('answer')->insert($data);
                        //$db='';
                    } else {
                        return $this->error('第' . $i . '题目未选择');
                    }
                } else {
                    //var_dump("i am checkbox");
                    $data = [
                        'answer1' => input('answer' . $i . '1'),
                        'answer2' => input('answer' . $i . '2'),
                        'answer3' => input('answer' . $i . '3'),
                        'answer4' => input('answer' . $i . '4'),
                        'answer5' => input('answer' . $i . '5'),
                        'answer6' => input('answer' . $i . '6'),
                        'cate' => $id,
                        'member' => session('loginmember'),
                        'memberid' => session('memberid'),
                        'name' => session('loginmember') . time(),
                        'answerid' => input('answerid' . $i),
                        'time' => time(),
                        'serialnumber' => session('serialnumber'),
                    ];

                    // 接收对应的答案，进行合并
                    $correct['answer1'] = input('answer' . $i . '1') ? 'A' : '';
                    $correct['answer2'] = input('answer' . $i . '2') ? 'B' : '';
                    $correct['answer3'] = input('answer' . $i . '3') ? 'C' : '';
                    $correct['answer4'] = input('answer' . $i . '4') ? 'D' : '';
                    $correct['answer5'] = input('answer' . $i . '5') ? 'E' : '';
                    $correct['answer6'] = input('answer' . $i . '6') ? 'F' : '';;
                    // 过滤掉空值
                    $filteredArray = array_filter($correct, function ($value) {
                        return $value !== null && $value !== "";
                    });

                    // 将数组元素合并为一个字符串
                    $data['correct'] = implode(", ", $filteredArray);

                    if (input('answer' . $i . '1') or input('answer' . $i . '2') or input('answer' . $i . '3') or input(
                            'answer' . $i . '4'
                        ) or input('answer' . $i . '5') or input('answer' . $i . '6')) {
                        # code...

                        // 查询出该试卷对应题目的得分，如果正确，获得得分
                        $data['score'] = \think\Db::name('article_contens')
                            ->where('cate', $id)
                            ->where('correct', $data['correct'])
                            ->where('id', input('answerid' . $i))
                            ->value('score')?:0;


                        $db = \think\Db::name('answer')->insert($data);


                    } else {
                        return $this->error('第' . $i . '题目未选择');
                    }
                    # code...


                }


                $i++;
            }


            $validate = \think\Loader::validate('answer');
            if ($validate->check($data)) {
                if ($db) {
                    //return $this->success('投票成功！','index');
//                    return $this->success('投票成功！', 'admin/member/score'.'/name/'. $data['name']);
                    return  $this->success('提交成功！',url('admin/member/score',['name'=>$data['name']]));
                    //重定向到News模块的Category操作
//                    $this->redirect('News/category', ['cate_id' => 2]);
                } else {
                    return $this->error('第' . $i . '题目未选择');
                }
            } else {
                return $this->error($validate->getError());
            }

            exit();
        }
        db('article')->where('id', $id)->setInc('click');
        $arts = \think\Db::name('article')->alias('a')->join('cate c', 'c.id = a.cateid', 'LEFT')->field(
            'a.title,a.desc,a.time,a.click,a.close,a.id,a.cateid,c.catename'
        )->where('a.id', $id)->find();
        // $prev= \think\Db::name('article')->where('id','<',$id)->where('cateid','=',$arts['cateid'])->order('id desc')->limit(1)->value('id');
        // $next= \think\Db::name('article')->where('id','>',$id)->where('cateid','=',$arts['cateid'])->order('id asc')->limit(1)->value('id');
        // $ralateres=$this->ralate($arts['keywords']);

        // var_dump($article_contens); die;
        // $arts['opend']= "none";

        $this->assign('arts', $arts);
        // $this->assign('prev',$prev);
        // $this->assign('next',$next);
        // $this->assign('ralateres',$ralateres);

        $this->assign('article_contens', $article_contens);

        return $this->fetch('article');
    }

    public function qrcode()
    {
        $id = input('artid');

        $article_contens = \think\Db::name('article_contens')
            ->where('cate', $id)
            ->order('id')
            ->where('title', 'neq', ' ')
            ->select();


        //var_dump(count($article_contens));
        //exit();

        if (request()->isPost()) {
            $arts['open'] = "";
            //var_dump(input('post.'));
            $i = 1;
            while ($i <= count($article_contens)) {
                # code...


                if (input('var' . $i) == 'radio') {
                    # code...
                    //var_dump(" i am raido");
                    $radiovalue = input('answer' . $i);
                    //$data['answer'.$radiovalue] = $radiovalue;
                    //var_dump('answer'.$radiovalue);exit;
                    // var_dump(session('memberid'));exit();
                    $data = [
                        'answer' . input('answer' . $i) => 1,
                        'cate' => $id,
                        'name' => session('loginmember') . time(),
                        'member' => session('loginmember'),
                        'memberid' => session('memberid'),
                        'answerid' => input('answerid' . $i),
                        'serialnumber' => session('serialnumber'),
                        'time' => time(),
                    ];

                    $db = '';
                    if ($radiovalue) {
                        # code...
                        //var_dump($radiovalue);
                        $db = \think\Db::name('answer')->insert($data);
                        //$db='';
                    } else {
                        return $this->error('第' . $i . '题目未选择');
                    }
                } else {
                    //var_dump("i am checkbox");
                    $data = [
                        'answer1' => input('answer' . $i . '1'),
                        'answer2' => input('answer' . $i . '2'),
                        'answer3' => input('answer' . $i . '3'),
                        'answer4' => input('answer' . $i . '4'),
                        'answer5' => input('answer' . $i . '5'),
                        'answer6' => input('answer' . $i . '6'),
                        'cate' => $id,
                        'member' => session('loginmember'),
                        'memberid' => session('memberid'),
                        'name' => session('loginmember') . time(),
                        'answerid' => input('answerid' . $i),
                        'time' => time(),
                        'serialnumber' => session('serialnumber'),
                    ];

                    if (input('answer' . $i . '1') or input('answer' . $i . '2') or input('answer' . $i . '3') or input(
                            'answer' . $i . '4'
                        ) or input('answer' . $i . '5') or input('answer' . $i . '6')) {
                        # code...
                        $db = \think\Db::name('answer')->insert($data);
                    } else {
                        return $this->error('第' . $i . '题目未选择');
                    }
                    # code...


                }


                $i++;
            }

            $validate = \think\Loader::validate('answer');
            if ($validate->check($data)) {
                if ($db) {
                    //return $this->success('投票成功！','index');
                    return $this->success('投票成功！', 'index/select');
                } else {
                    return $this->error('第' . $i . '题目未选择');
                }
            } else {
                return $this->error($validate->getError());
            }

            exit();
        }
        db('article')->where('id', $id)->setInc('click');
        $arts = \think\Db::name('article')->alias('a')->join('cate c', 'c.id = a.cateid', 'LEFT')->field(
            'a.title,a.desc,a.time,a.click,a.close,a.id,a.cateid,c.catename'
        )->where('a.id', $id)->find();


        $this->assign('arts', $arts);
        $this->assign('id', $id);

        $this->assign('article_contens', $article_contens);


        return $this->fetch();
    }

    public function ralate($keywords)
    {
        $arr = explode(',', $keywords);
        // var_dump($arr); die;
        static $ralateres = array();
        foreach ($arr as $k => $v) {
            $map['keywords'] = ['like', '%' . $v . '%'];
            $artres = \think\Db::name('article')->order('id desc')->where($map)->limit(10)->field(
                'id,title,time'
            )->select();
            $ralateres = array_merge($ralateres, $artres);
            $ralateres = arr_unique($ralateres);
        }
        return $ralateres;
    }


}
